package com.hr.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hr.common.utils.EntityConvertUtil;
import com.hr.common.utils.MenuUtil;
import com.hr.system.entity.SysMenu;
import com.hr.system.entity.vo.MenuTree;
import com.hr.system.mapper.SysMenuMapper;
import com.hr.system.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hr
 * @since 2024-04-26
 */
@Service
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public List<SysMenu> getList(SysMenu sysMenu) {
        return sysMenuMapper.selectList(Wrappers.<SysMenu>lambdaQuery()
                .eq(sysMenu.getType()!=null, SysMenu::getType,sysMenu.getType())
                .eq(sysMenu.getParentId()!=null,SysMenu::getParentId,sysMenu.getParentId())
        );
    }

    @Override
    public Integer add(SysMenu sysMenu) {
        return sysMenuMapper.insert(sysMenu);
    }

    @Override
    public Integer update(SysMenu sysMenu) {
        return sysMenuMapper.updateById(sysMenu);
    }

    @Override
    public List<MenuTree> queryTree() {
        return MenuUtil.getMenuTree(sysMenuMapper.selectList(Wrappers.<SysMenu>lambdaQuery()
                .eq(true,SysMenu::getType,1)
                .orderByAsc(SysMenu::getSort)
        ));
    }

    @Override
    public Map<String, Object> queryMenuPerms() {
        LambdaQueryWrapper<SysMenu> wrapper=new LambdaQueryWrapper<>();
        wrapper.orderByAsc(SysMenu::getType).orderByAsc(SysMenu::getLevel).orderByAsc(SysMenu::getSort);
        List<SysMenu> menus=sysMenuMapper.selectList(wrapper);
        Map<String,Object> result=new HashMap<>();
        //菜单
        result.put("menus",MenuUtil.getMenuTree(menus.stream().filter(m->m.getType()==1).collect(Collectors.toList())));
        //权限
        result.put("perms",menus.stream().filter(m->m.getType()==2).map(m-> EntityConvertUtil.convert(m,MenuTree.class)).collect(Collectors.toList()));

        return result;
    }

    @Override
    public Integer delete(Integer id) {
        return sysMenuMapper.deleteById(id);
    }
}
